package com.unknowpupil.sell.service.impl;

import com.lly835.bestpay.enums.BestPayTypeEnum;

import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.lly835.bestpay.service.impl.WxPayServiceImpl;
import com.unknowpupil.sell.common.enums.ErrorCodeEnum;
import com.unknowpupil.sell.dto.OrderDTO;
import com.unknowpupil.sell.exception.SellException;
import com.unknowpupil.sell.service.IOrderMasterService;
import com.unknowpupil.sell.service.PayServer;
import com.unknowpupil.sell.utils.JsonUtils;
import com.unknowpupil.sell.utils.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @Classname: PayServerImpl
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/1/1 16:29
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class PayServerImpl implements PayServer {
    @Autowired
    private BestPayServiceImpl bestPayService;
    @Autowired
    private IOrderMasterService orderMasterService;
    @Override
    public PayResponse create(OrderDTO orderDTO) {
        PayRequest payRequest = payRequest(orderDTO);
        log.info("[微信支付]-->发起支付 payRequest={}", JsonUtils.toJson(payRequest));

        PayResponse pay = bestPayService.pay(payRequest(orderDTO));
        log.info("[微信支付]--->发起支付 支付结果 payResponse = {}", JsonUtils.toJson(pay));
        return pay;
    }

    @Override

    public PayResponse callBack(String notifyData) {
        //验证签名
        //支付状态  asyncNotify 这个方法帮我们做了
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("[微信支付]--->异步通知 支付结果 payResponse = {}", JsonUtils.toJson(payResponse));
        OrderDTO orderDTO = orderMasterService.finOne(payResponse.getOrderId());
        if(orderDTO==null){
            log.error("[支付回调] 订单不存在");
            throw new SellException(ErrorCodeEnum.ORDER_NOT_EXIST);
        }
        //支付金额
        //支付的人（下单人支付人）
        if(!MathUtil.equals(payResponse.getOrderAmount(),orderDTO.getOrderAmount().doubleValue())){
            log.error("[微信支付] 异步通知，订单金额不准确，order_id={} 微信金额={}，系统金额={}",payResponse.getOrderId(),payResponse.getOrderAmount(),orderDTO.getOrderAmount());
            throw new SellException(ErrorCodeEnum.WXPAY_NOTIFY_MONEY_VERIFY_ERROR);
        }
        OrderDTO paid = orderMasterService.paid(orderDTO);
        //修改完成之后需要告诉微信
        return payResponse;
    }

    @Override
    /**
     * 功能描述: <br>
     * 〈退款〉
     *
     * @param: [orderDTO]
     * @since: 1.0.0
     * @auther: w10g
     * @return: void
     * @Date: 2020/1/2 16:43
     */
    public RefundResponse refound(OrderDTO orderDTO) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        refundRequest.setOrderId(orderDTO.getOrderId());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_MP);
        log.info("【微信退款】 request={}",JsonUtils.toJson(refundRequest));
        RefundResponse refund = bestPayService.refund(refundRequest);
        log.info("【微信退款】 response={}",JsonUtils.toJson(refund));
        return refund;
    }

    private PayRequest payRequest(OrderDTO orderDTO) {
        PayRequest payRequest = new PayRequest();
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_MP);
        payRequest.setOrderId(orderDTO.getOrderId());
        payRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        payRequest.setOrderName(orderDTO.getBuyerName());
        payRequest.setOpenid(orderDTO.getBuyerOpenid());
        payRequest.setSpbillCreateIp(null);
        payRequest.setAttach("测试");
        return payRequest;
    }
}
